package com.macro.mall.portal.config;

import com.macro.mall.common.service.RedisService;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.security.component.DynamicSecurityService;
import com.macro.mall.security.component.ValidateTokenService;
import com.macro.mall.security.config.SecurityConfig;
import com.macro.mall.security.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mall-security模块相关配置
 * Created by macro on 2019/11/5.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Component
public class MallSecurityConfig extends SecurityConfig implements ValidateTokenService {
    public static String TOKEN_KEY = "portal:token:key:username:";
    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private JwtTokenUtil tokenUtil;

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> memberService.loadUserByUsername(username,null);
    }

    @Override
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = this.tokenUtil.getUserNameFromToken(token);
        String flag = String.valueOf(this.redisService.get(TOKEN_KEY + username));
        if(StringUtils.isBlank(flag)||"null".equals(flag)){
            flag = String.valueOf(this.redisService.get(TOKEN_KEY + ((MemberDetails) userDetails).getUmsMember().getPhone()));
        }
        return username.equals(userDetails.getUsername()) && !this.tokenUtil.isTokenExpired(token) && flag.equals(token);
    }
}
